/**
*	@name							Enhanced Forms
*	@descripton						Enhanced Forms is jQuery plugin that makes it possible to dinamically change form fields.
*	@version						1.8.0
*	@requires						jQuery 1.8.0+
*
*	@author							Sam Vervaeck
*	@author-email					sam@vervaeck.be
*	@author-website					http://sam.vervaeck.be
*
*	@licence						GNU General Public License - http://www.gnu.org/licenses/gpl-3.0.html
*/

(function($){ 
	$.fn.extend({
	
		// Makes it possible to collapse fieldsets
		collapsable: function () {
			
			this.each(function () {
			
				if (this.type == 'fieldset') {
				
					var fieldset = $(this);
					
					// Make the fieldsets collapsable
					fieldset.children("legend").click(function () {
						$(this).nextAll().toggle();
					});
					
					// Collapse marked fieldsets
					if (fieldset.hasClass("collapsed")) {
						fielset
							.removeClass("collapsed")
							.children("legend").nextAll().hide();
					}
					
				// Search for other fieldsets
				} else {
					$(this).children().collapsable();
				}
			});
			
			// Continue jQuery
			return this;
		},
		
		// Convenient method to search for a form field
		fields: function (name) {
		
			return this.each(function () {
			
				// This function only works on forms
				if (this.type !== 'form') {
					return false;
				}
				
				var fields =  $(this).find("input, textarea, select");
				
				// Unify ID and NAME attribute (both are valid)
				return $(fields.filter("[id=" + name + "]"), fields.filter("[name=" + name + "]"));
			});
		},
		
		// Create dynamic subfields for a certain field
		subform: function(predicate) {
			
			// By default the main field is a checkbox or radio button
			if (predicate === undefined) {
				predicate = ":checked";
			}
			
			var fields = this;
			
			// Function to show subform for certain field
			function select (field) {
				fields.first().nextUntil(fields.last()).not(fields).hide();
				field.nextUntil(fields).show();
			}
			
			// Bind event to the 
			fields.change(function () {
				if ($(this).find("input").is(predicate)) {
					select ($(this));
				}
			}).find(":checked").parent().each(function () { select (this); });
			
			// Continue jQuery
			return this;
        }
    });
})(jQuery);